import Koa from 'koa';
import bodyParser from 'koa-bodyparser';
import StatusError, { INVALID_API } from './utils/StatusError';
import router from './router';
import { ValidationError } from 'sequelize';

const app = new Koa();

app.proxy = true;

export default app;

// Translate error into json response.
app.use((ctx, next) => {
  return next()
    .then(() => {
      if (__DEV__) {
        console.log(ctx.body);
      }
      ctx.body = ctx.body || { ok: 1 };
      ctx.body.ok = 1;
    }, err => {
      if (__DEV__) {
        console.error(err.stack);
      }
      ctx.body = {
        message: err.message,
      };
      // TODO: 如果请求body解析失败（json错），则返回400 Bad Request
      if (err instanceof StatusError) {
        ctx.body.status = ctx.status = err.code;
      } else {
        ctx.body.status = ctx.status = 500;
      }
    });
});

app.use(bodyParser());

if (__DEV__) {
  app.use((ctx, next) => {
    console.log(ctx.url, ctx.request.body);
    return next();
  });
}

app.use(router.routes());

app.use(() => Promise.reject(INVALID_API));